import { Tooltip } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import './index.less';

export interface Column {
  title: string;
  dataIndex: string;
  key: string;
  width?: number;
  align?: 'left' | 'center' | 'right';
  render?: (text: string, record: any, index: number) => React.ReactNode;
  sorter?: (a: any, b: any) => number;
  ellipsis?: boolean;
  sortDirections?: ('ascend' | 'descend')[];
}

export interface TableProps {
  columns: Column[];
  dataSource: any[];
  rowKey: string | ((record: any) => string);
  showHeader?: boolean;
  bordered?: boolean;
  rowHeight?: number;
  containerHeight?: number;
  onSortChange?: (sorterField: string, order: 'ascend' | 'descend') => void;
  tooltipOnOverflow?: boolean;
  scrollSpeed?: number; // 表格自动滚动的速度, 0 代表停止滚动
  stickyHeader?: boolean; // 固定表头
}

const Table: React.FC<TableProps> = ({
  columns,
  dataSource,
  rowKey,
  showHeader = true,
  bordered = false,
  rowHeight = 50,
  containerHeight = 600,
  onSortChange,
  tooltipOnOverflow = false,
  scrollSpeed = 50,
  stickyHeader = true,
}) => {
  const [sortField, setSortField] = useState<string | null>(null);
  const [sortOrder, setSortOrder] = useState<'ascend' | 'descend' | null>(null);
  const tableRef = useRef<HTMLDivElement>(null);

  const handleSort = (field: string, order: 'ascend' | 'descend') => {
    setSortField(field);
    setSortOrder(order);
    onSortChange?.(field, order);
  };

  useEffect(() => {
    const tableDiv = tableRef.current;
    let scrollInterval: NodeJS.Timeout | null = null;

    const startScrolling = () => {
      if (scrollSpeed > 0 && tableDiv) {
        scrollInterval = setInterval(() => {
          // 获取原始内容的高度
          const tableBody = tableDiv.querySelector('tbody');
          const scrollHeight = tableBody ? tableBody.scrollHeight : 0;

          // 如果滚动到克隆表格的位置，则回到顶部，制造无缝滚动
          if (tableDiv.scrollTop >= scrollHeight) {
            tableDiv.scrollTop = 0;
          } else {
            tableDiv.scrollTop += 1; // 控制滚动速度
          }
        }, 100 / scrollSpeed); // 根据 scrollSpeed 动态调整速度
      }
    };

    const stopScrolling = () => {
      if (scrollInterval) {
        clearInterval(scrollInterval);
      }
    };

    startScrolling();

    return () => {
      stopScrolling();
    };
  }, [scrollSpeed, dataSource]);

  const renderSortArrows = (field: string) => (
    <div className="sort-arrows">
      <span
        className={`sort-arrow ${sortField === field && sortOrder === 'ascend' ? 'active' : ''}`}
        onClick={() => handleSort(field, 'ascend')}
      >
        ▲
      </span>
      <span
        className={`sort-arrow ${sortField === field && sortOrder === 'descend' ? 'active' : ''}`}
        onClick={() => handleSort(field, 'descend')}
      >
        ▼
      </span>
    </div>
  );

  return (
    <div
      className={`custom-table-container ${bordered ? 'bordered' : ''} ${
        stickyHeader ? 'sticky-header' : ''
      }`}
      style={{ height: containerHeight, overflow: 'auto', position: 'relative' }}
      ref={tableRef}
    >
      <table className="custom-table">
        {showHeader && (
          <thead>
            <tr>
              {columns.map((col) => (
                <th key={col.key} style={{ width: col.width }}>
                  {col.title}
                  {col.sorter && renderSortArrows(col.dataIndex)}
                </th>
              ))}
            </tr>
          </thead>
        )}
        <tbody>
          {dataSource.map((record, index) => (
            <tr
              key={typeof rowKey === 'function' ? rowKey(record) : record[rowKey]}
              style={{ height: rowHeight }}
            >
              {columns.map((col) => (
                <td key={col.key} style={{ textAlign: col.align }}>
                  {col.ellipsis ? (
                    <Tooltip title={tooltipOnOverflow ? record[col.dataIndex] : null}>
                      <div className="ellipsis-cell">
                        {col.render
                          ? col.render(record[col.dataIndex], record, index)
                          : record[col.dataIndex]}
                      </div>
                    </Tooltip>
                  ) : col.render ? (
                    col.render(record[col.dataIndex], record, index)
                  ) : (
                    record[col.dataIndex]
                  )}
                </td>
              ))}
            </tr>
          ))}
        </tbody>
        {/* 克隆一份内容 */}
        <tbody>
          {dataSource.map((record, index) => (
            <tr
              key={`cloned-${typeof rowKey === 'function' ? rowKey(record) : record[rowKey]}`}
              style={{ height: rowHeight }}
            >
              {columns.map((col) => (
                <td key={col.key} style={{ textAlign: col.align }}>
                  {col.ellipsis ? (
                    <Tooltip title={tooltipOnOverflow ? record[col.dataIndex] : null}>
                      <div className="ellipsis-cell">
                        {col.render
                          ? col.render(record[col.dataIndex], record, index)
                          : record[col.dataIndex]}
                      </div>
                    </Tooltip>
                  ) : col.render ? (
                    col.render(record[col.dataIndex], record, index)
                  ) : (
                    record[col.dataIndex]
                  )}
                </td>
              ))}
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
};

export default Table;
